//
//  MKDownloadBrowseViewController.m
//  ManKeCartoon
//
//  Created by 邹功梁 on 15/10/28.
//  Copyright © 2015年 ManKe. All rights reserved.
//

#import "MKDownloadBrowseViewController.h"
#import "MKDownBrowseCollectionViewCell.h"
#import "Reachability.h"
#import "CoreDataManager.h"
@interface MKDownloadBrowseViewController ()<UICollectionViewDataSource, UICollectionViewDelegate>

@property (nonatomic, strong) UIButton *backButton; // Nav返回按钮
@property (nonatomic, strong) UILabel *seq_noLabel; // Nav第%ld话(**/**) Label
@property (nonatomic, strong) UILabel *nameLabel; // Nav漫画名

@property (nonatomic, strong) UIView *bottomBackView; // 底部显示电池电量的状态栏
@property (nonatomic, strong) UIView *batteryLevelView;
@property (nonatomic, strong) UILabel *timeLabel;
@property (nonatomic, strong) UIImageView *batteryImage;

@property (nonatomic, copy) NSString *reachString;

@property (nonatomic, retain) NSMutableArray *chaptersArray;

@end

@implementation MKDownloadBrowseViewController
- (void)viewWillAppear:(BOOL)animated
{
    [self reachablilty];
    self.tabBarController.tabBar.hidden = YES;
    //    self.navBarView.hidden = YES;
}
- (void)viewWillDisappear:(BOOL)animated
{
    self.tabBarController.tabBar.hidden = NO;
    self.navBarView.hidden = NO;
}
- (instancetype)init
{
    self = [super init];
    if (self) {
        _comicDic = [[NSMutableDictionary alloc] init];
        _chaptersArray = [[NSMutableArray alloc] init];
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setUpBackButton];
    [self dataBase];
    [self customNavBar];
    [self setUpCollectionView];
    [self customBottomState];
}
#pragma mark - 数据处理
- (void)dataBase
{
    NSArray *array = [_comicDic.allKeys sortedArrayUsingSelector:@selector(compare:)];
    _chaptersArray = [_comicDic objectForKey:array.firstObject];
}
#pragma mark - 粗略检测网络状态
- (void)reachablilty
{
    Reachability *reach = [Reachability reachabilityWithHostName:@"www.apple.com"];
    switch ([reach currentReachabilityStatus]) {
        case NotReachable:
            NSLog(@"没有网络连接");
            break;
        case ReachableViaWiFi:
            _reachString = @"WIFI";
            break;
        case ReachableViaWWAN:
            _reachString = @"GPRS";
            break;
        default:
            NSLog(@"[Error] 检测错误");
            break;
    }
}
#pragma mark - 隐藏电池栏
- (UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleDefault;
    //UIStatusBarStyleDefault = 0 黑色文字，浅色背景时使用
    //UIStatusBarStyleLightContent = 1 白色文字，深色背景时使用
}
- (BOOL)prefersStatusBarHidden
{
    return YES; // 返回NO表示要显示，返回YES将hiden
}
#pragma mark - 创建相关NavBar样式
- (void)customNavBar
{
    [self.navBarView setFrame:CGRectMake(0, 0, SCREEN_WIDTH, 70)];
    
    _seq_noLabel = [[UILabel alloc] initWithFrame:CGRectMake(60, 40, SCREEN_WIDTH - 120, 20)];
    _seq_noLabel.textAlignment = NSTextAlignmentCenter;
    [_seq_noLabel setTextColor:[UIColor whiteColor]];
    NSString *countStr = [NSString stringWithFormat:@"第%d话 (%d/%ld)", 0, 1, _chaptersArray.count];
    
    [_seq_noLabel setText:countStr];
    [self.navBarView addSubview:_seq_noLabel];
    
    _nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(60, 10, SCREEN_WIDTH - 120, 30)];
    _nameLabel.textAlignment = NSTextAlignmentCenter;
    [_nameLabel setTextColor:[UIColor whiteColor]];
    [_nameLabel setText:_downData.title];
    [self.navBarView addSubview:_nameLabel];
    
    _nameLabel.superview.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:.5];
}
#pragma mark - 获取当前电池电量
- (float)getBatteryLeveal
{
    return [UIDevice currentDevice].batteryLevel;
}
#pragma mark - CustomBottomState 底部状态栏
- (void)customBottomState
{
    _batteryImage = [[UIImageView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - 30, 0, 20, 10)];
    [_batteryImage setImage:[UIImage imageNamed:@"battery@2x.png"]];
    
    _batteryLevelView = [[UIView alloc] initWithFrame:CGRectMake(1, 1, (_batteryImage.frame.size.width - 3) * (-[self getBatteryLeveal]), 8)];
    [_batteryLevelView setBackgroundColor:[UIColor whiteColor]];
    
    // 底部状态栏
    
    NSString *bottomString = [NSString stringWithFormat:@"第%d话 %d/%ld %@ %@", 0, 1, _chaptersArray.count, _reachString, [self getDate]];
    CGFloat width = [StringWithWidth WidthWithText:bottomString height:10 font:[UIFont systemFontOfSize:10.]];
    
    _timeLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, width, 10)];
    [_timeLabel setTextColor:[UIColor whiteColor]];
    [_timeLabel setTextAlignment:NSTextAlignmentRight];
    [_timeLabel setFont:[UIFont systemFontOfSize:10.]];
    [_timeLabel setText:bottomString];
    
    _bottomBackView = [[UIView alloc] initWithFrame:CGRectMake(_timeLabel.frame.origin.x - 5, SCREEN_HEIGHT - 15, SCREEN_WIDTH - _timeLabel.frame.origin.x, 15)];
    
    [self.view addSubview:_bottomBackView];
    [_bottomBackView addSubview:_batteryImage];
    [_batteryImage addSubview:_batteryLevelView];
    [_bottomBackView addSubview:_timeLabel];
}
#pragma mark - 获取时间
- (NSString *)getDate
{
    NSDate *date = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"hh:mm";
    NSString *dateString = [formatter stringFromDate:date];
    return dateString;
}
- (void)getBatteryInfo
{
    [_batteryLevelView setFrame:CGRectMake(1, 1, (_batteryImage.frame.size.width - 3) * (-[self getBatteryLeveal]), 8)];
    //    NSString *bottomString = [NSString stringWithFormat:@"第%ld话 %d/%ld %@ %@", _seq_no, 1, _current_imgArray.count, _reachString, [self getDate]];
    //    [_timeLabel setText:bottomString];
}
- (void)reloadBatteryInfo
{
    [NSTimer scheduledTimerWithTimeInterval:60.0f target:self selector:@selector(getBatteryInfo) userInfo:nil repeats:YES];
}
#pragma mark - 创建一个返回按钮
- (void)setUpBackButton
{
    _backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_backButton setFrame:CGRectMake(10, 18, 30, 30)];
    [_backButton setImage:[UIImage imageNamed:@"iconfont-arrowleft.png"] forState:UIControlStateNormal];
    [_backButton addTarget:self action:@selector(backButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [self.navBarView addSubview:_backButton];
}
#pragma mark - 返回按钮点击方法
- (void)backButtonClick
{
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark - SetUpCollectionView
- (void)setUpCollectionView
{
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.itemSize = CGSizeMake(SCREEN_WIDTH, SCREEN_HEIGHT);
    flowLayout.minimumInteritemSpacing = 0;
    flowLayout.minimumLineSpacing = 0;
    flowLayout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
    flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    
    _collectionView = [[UICollectionView alloc] initWithFrame:self.view.frame collectionViewLayout:flowLayout];
    _collectionView.pagingEnabled = YES;
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    [self.view insertSubview:_collectionView atIndex:0];
    
    [_collectionView registerClass:[MKDownBrowseCollectionViewCell class] forCellWithReuseIdentifier:@"reuseIdentifier"];
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    NSArray *array = [_comicDic.allKeys sortedArrayUsingSelector:@selector(compare:)];
    NSArray *seq_noArray = [_comicDic objectForKey:array[section]];
    return seq_noArray.count;
}
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return _comicDic.allKeys.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    MKDownBrowseCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuseIdentifier" forIndexPath:indexPath];
    NSArray *array = [_comicDic.allKeys sortedArrayUsingSelector:@selector(compare:)];
    NSArray *seq_noArray = [_comicDic objectForKey:array[indexPath.section]];
    UIImage *image = [seq_noArray objectAtIndex:indexPath.row];
    
    // 设置滚动对应集数
    NSString *seq_noStr = [NSString stringWithFormat:@"第%@话 (%ld/%ld)", array[indexPath.section], indexPath.row + 1, seq_noArray.count];
    [_seq_noLabel setText:seq_noStr];
    // 设置底部栏
    NSString *bottomString = [NSString stringWithFormat:@"第%@话 %ld/%ld %@ %@", array[indexPath.section], indexPath.row + 1, seq_noArray.count, _reachString, [self getDate]];
    CGFloat width = [StringWithWidth WidthWithText:bottomString height:10 font:[UIFont systemFontOfSize:10.]];
    [_timeLabel setFrame:CGRectMake(SCREEN_WIDTH - 30 - width - 5, 0, width, 10)];
    [_timeLabel setText:bottomString];
    
    [cell setImageInfosImage:image];
    
    [cell.tap_Image addTarget:self action:@selector(tapClick)];
    return cell;
}
- (void)tapClick
{
    self.navBarView.hidden = !self.navBarView.hidden;
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    self.navBarView.hidden = YES;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
